package db

import (
	"database/sql"
	"fmt"
	_ "github.com/go-sql-driver/mysql"
	log "github.com/sirupsen/logrus"
)

type DBClient struct {
	username  string
	password  string
	dbAddress string
	dbName    string
	dbDSN     string
	DB        *sql.DB
}

func (d *DBClient) InitDBInfo(user, password, address, dbname string) {
	d.username = user
	d.password = password
	d.dbAddress = address
	d.dbName = dbname
	d.dbDSN = fmt.Sprintf("%s:%s@tcp(%s)/?parseTime=true", d.username, d.password, d.dbAddress)
}

func (d *DBClient) InitDB() error {
	db, err := sql.Open("mysql", d.dbDSN)
	db.Ping()
	//defer db.Close()
	if err != nil {
		fmt.Println("数据库连接失败！")
		log.Fatalln(err)
		return err
	}
	d.DB = db
	return nil
}

func (d *DBClient) CloseDB() {
	err := d.DB.Close()
	if err != nil {
		log.Errorf("close database error: %s", err.Error())
	}
	log.Info("close database success")
}

func (d *DBClient) CheckoutDatabase() (bool, error) {
	sqlStr := "show databases;"
	rows, err := d.DB.Query(sqlStr)
	if err != nil {
		log.Errorf("query error: %s", err.Error())
		return false, err
	}
	isExist := false
	for rows.Next() {
		database := Database{}
		err := rows.Scan(&database.Database)
		log.Debug(database.Database)
		if err != nil {
			log.Errorf("scan error: %s", err.Error())
			return false, err
		}
		if database.Database == d.dbName {
			log.Infof("database %s is exist", d.dbName)
			isExist = true
		}
	}
	if isExist == false {
		log.Infof("database %s is not exist", d.dbName)
	}
	return isExist, nil
}

func (d *DBClient) CreateDatabase() (int64, error) {
	sqlStr := "CREATE DATABASE IF NOT EXISTS %s;"
	result, err := d.DB.Exec(fmt.Sprintf(sqlStr, d.dbName))
	if err != nil {
		log.Errorf("exec error: %s", err.Error())
		return -1, err
	}
	num, err := result.RowsAffected()
	if err != nil {
		log.Errorf("query error: %s", err.Error())
		return -1, err
	}
	return num, nil
}

//
//func checkoutTables() {
//
//}
